#pragma once
#include <signal.h>
#include <functional>
#include "Log.hpp"
#include "Socket.hpp"
#include "Log.hpp"

using func_t = std::function<std::string(std::string &package)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback) : _port(port), _callback(callback)
    {
    }

    bool InitServer()
    {
        _listensockfd.Socket();
        _listensockfd.Bind(_port);
        _listensockfd.Listen();
        lg(Info, "init server ...done");
        return true;
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN); // 对子进程发出的信号进行忽略
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = _listensockfd.Accept(&clientip, &clientport);
            if (sockfd < 0)
                continue;
            lg(Info, "accept a new link, sockfd: %d, clientop: %s, clientport: %d", sockfd, clientip.c_str(), clientport);
            if (fork() == 0)
            {
                _listensockfd.Close();
                std::string inbuffer_stream;
                // 数据计算
                while (true)
                {
                    char buffer[1280];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;
                        
                        lg(Debug, "debug :\n%s", inbuffer_stream.c_str());

                        while (true)
                        {
                            std::string info = _callback(inbuffer_stream);
                            if (info.empty())
                                break;
                            lg(Debug, "degun,response:\n%s", info.c_str());
                            lg(Debug, "debug :\n%s", inbuffer_stream.c_str());
                            write(sockfd, info.c_str(), info.size());
                        }
                    }
                    else
                        break;
                }
                exit(0);
            }
            close(sockfd);
        }
    }

    ~TcpServer() {}

private:
    uint16_t _port;
    Sock _listensockfd;
    func_t _callback;
};